<?php

namespace Cblood\Sword\Operation;


class OrganizeInsert extends OrganizeSqlBasic
{

    /**
     * 生成插入数据的sql
     * 所需要的格式
     * $insertKeys = array('key1' , 'key2');
     * $insertValues = array(
     *     0 => array('value1', 'value2'),
     *     1 => array('value3', 'value4')
     * );
     * @param array $insertKeys
     * @param array $insertValues
     * @return string
     */
    public function create(array $insertKeys, array $insertValues)
    {
        $keySql = $this->organizeKey($insertKeys);
        $valueSql = $this->organizeValue($insertValues, count($insertKeys));
        $resultSql = $keySql . ' VALUES ' . $valueSql;

        $resultSql = 'INSERT INTO ' . $this->getTable() . ' ' . $resultSql;

        return $resultSql;
    }

    /**
     * 创建一条只插入一条数据的sql
     *
     * @param array $insert ['field' => 'value' , 'field2' => 'value2']
     * @return string
     * @throws \Exception
     */
    public function createOne(array $insert)
    {
        $insertKeys = [];
        $insertValues = [];
        foreach ($insert as $name => $value) {
            if (is_array($name) || is_array($value)) {
                throw new \Exception('参数不正确，不可以为数组');
            }
            $insertKeys[] = $name;
            $insertValues[0][] = $value;
        }
        return $this->create($insertKeys, $insertValues);
    }

    protected function organizeKey(array $insertKeys)
    {
        return '(' . $this->finishingField($insertKeys) . ')';
    }

    protected function organizeValue(array $insertValues, int $keyCount)
    {
        $valueSql = '';

        for ($i = 0; $i < count($insertValues); $i++) {
            $temporarySql = '';
            if (count($insertValues[$i]) != $keyCount) {
                throw new \Exception('插入数据信息不对称，请检查...');
            }
            for ($k = 0; $k < count($insertValues[$i]); $k++) {
                $values = '\'' . $insertValues[$i][$k] . '\'';
                $temporarySql .= empty($temporarySql) ? $values : (',' . $values);
            }
            $temporarySql = '(' . $temporarySql . ')';
            $valueSql .= empty($valueSql) ? $temporarySql : (',' . $temporarySql);
        }
        return $valueSql;
    }
}